<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }"
                >首页</el-breadcrumb-item
            >
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <!-- 搜索和添加 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input
                        placeholder="请输入搜索内容"
                        v-model="queryInfo.query"
                        clearable
                        @clear="getUserList"
                    >
                        <el-button
                            slot="append"
                            icon="el-icon-search"
                            @click="getUserList"
                        ></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addUser = true"
                        >添加用户</el-button
                    >
                </el-col>
            </el-row>
            <!-- 用户列表 -->
            <el-table :data="userList" border>
                <!-- 索引列 -->
                <el-table-column
                    type="index"
                    label="序号"
                    width="60"
                ></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column
                    prop="role_name"
                    label="角色"
                ></el-table-column>
                <el-table-column label="状态">
                    <!-- 自定义列模板，使用作用域插槽，通过scope.row获取当前行的数据 -->
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.mg_state"
                            @change="doChange(scope.row)"
                        ></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <!-- 修改 -->
                        <el-button
                            type="primary"
                            icon="el-icon-edit"
                            size="mini"
                            @click="selectUser(scope.row.id)"
                        ></el-button>
                        <!-- 删除 -->
                        <el-button
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                            @click="removeUser(scope.row.id)"
                        ></el-button>
                        <!-- 分配角色 -->
                        <el-button
                            type="warning"
                            icon="el-icon-setting"
                            size="mini"
                            @click="selectUserTow(scope.row)"
                        ></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            >
            </el-pagination>
        </el-card>
        <!-- 添加用户弹出窗 -->
            <el-dialog 
                title="添加用户"
                :visible.sync="addUser"
                width="50%"
                @close="emptyContent"
            >
                <el-form
                    ref="addFormRef"
                    :model="addForm"
                    label-width="70px"
                    :rules="addFormRules"
                >
                    <el-form-item label="用户名" prop="username" required>
                        <el-input v-model="addForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password" required>
                        <el-input v-model="addForm.password" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email" required>
                        <el-input v-model="addForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile" required>
                        <el-input v-model="addForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addUser = false">取 消</el-button>
                    <el-button type="primary" @click="addUsers()">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 修改用户 -->
            <el-dialog
                title="修改用户"
                :visible.sync="modifyUser"
            >
                <el-form
                    :model="modifyForm"
                    :rules="addFormRules"
                    label-width="80px"
                    ref="modifyUserRef"
                >
                    <el-form-item label="用户名" prop="name" >
                        <el-input v-model="modifyForm.username" autocomplete="off" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email" >
                        <el-input v-model="modifyForm.email" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile" >
                        <el-input v-model="modifyForm.mobile" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
				    <el-button @click="modifyUser = false">取 消</el-button>
				    <el-button type="primary" @click="modifyUserInfo()">确 定</el-button>
			    </div>
            </el-dialog>
            <!-- 分配角色弹出框 -->
            <el-dialog title="分配角色" :visible.sync="distributionUser" @close="outdistribution">
                <el-form :model="userInfo" ref="distributionUserRef">
                    <el-form-item label="当前的用户:" label-width="100px">{{ userInfo.username }}</el-form-item>
                    <el-form-item label="当前的角色:" label-width="100px">{{ userInfo.role_name }}</el-form-item>
                    <el-form-item label="分配新角色:" label-width="90px">
                        <el-select v-model="selectedRoleId" placeholder="请选择角色">
                            <el-option v-for="(item) in distributionForm" :key="item.id" :label="item.roleName" :value="item.id"></el-option> 
                        </el-select>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="distributionUser = false">取 消</el-button>
                    <el-button type="primary" @click="distributionUserInfo">确 定</el-button>
                </div>
            </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        let checkEmail = (rule, value, cb) => {
			// 验证邮箱的正则表达式
			const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
			if (regEmail.test(value)) {
				// 合法邮箱
				return cb();
			}
			cb(new Error("请输入合法邮箱"));
		};
		// 验证手机号的规则
		let checkMobile = (rule, value, cb) => {
			const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
			if (regMobile.test(value)) {
				return cb();
			}
			cb(new Error("请输入合法手机号"));
		};
        return {
            keyword: "",
            // 查询用户列表的参数对象
            queryInfo: {
                query: "",
                pagenum: 1,
                pagesize: 5,
            },
            addUser: false,
            modifyUser:false,
            userList: [],
            modifyForm:{},
            total: 0,
            addForm:{
				username: "",
				password: null,
				email: "",
				mobile: null,
            },
            // 分配角色
            distributionUser:false,
            //所有角色数据
            selectedRoleId:'',
            // 所点击的用户信息
            userInfo:{},
            //所有角色数据
            distributionForm:[],
            //验证规则
            addFormRules:{
                username: [
					{ required: true, message: "请输入用户名", trigger: "blur" },
					{
						min: 3,
						max: 10,
						message: "用户名的长度在3-10位之间",
						trigger: "blur",
					},
				],
				password: [
					{ required: true, message: "请输入密码", trigger: "blur" },
					{
						min: 6,
						max: 16,
						message: "密码的长度在6-16位之间",
                        trigger: "blur",
					},
				],
				email: [
					{ required: true, message: "请输入邮箱", trigger: "blur" },
					{ validator: checkEmail, trigger: "blur" },
					{
						min: 6,
						max: 16,
						message: "邮箱的长度在6-16位之间",
						trigger: "blur",
					},
				],
				mobile: [
					{ required: true, message: "请输入电话号", trigger: "blur" },
					{ validator: checkMobile, trigger: "blur" },
					{ min: 11, max: 11, message: "电话的长度应为11位", trigger: "blur" },
				],
            }
        };
    },
    created() {
        this.getUserList(); 
    },
    methods: {
        async getUserList() {
            const { data: res } = await this.$http.get("users", {
                params: this.queryInfo,
            });
            console.log(res);

            if (res.meta.status != 200) {
                return this.message.error("获取用户列表失败");
            }
            this.userList = res.data.users;
            this.total = res.data.total;
        },
        async doChange(userinfo) {
            const { data: res } = await this.$http.put(
                `users/${userinfo.id}/state/${userinfo.mg_state}`
            );
            console.log(res);
            if (res.meta.status != 200) {
                return this.message.error("用户状态更新失败");
            }
            this.$message.success("用户状态更新成功");
        },
        handleSizeChange(val) {
            this.queryInfo.pagesize = val;
            this.getUserList();
        },
        handleCurrentChange(val) {
            this.queryInfo.pagenum = val;
            this.getUserList();
        },
        //添加用户请求
        addUsers(){
            this.$refs.addFormRef.validate(async (valid) =>{
                if(!valid){
                    return
                }
                const { data: res } = await this.$http.post("users",this.addForm);
                console.log(res)
                if(res.status !==201){
                    this.$message.error("添加用户失败");
                }
                this.$message.success("添加用户成功");
                //关闭对话框
                this.addUser=false;
                this.getUserList();
            })
        },
        //关闭添加用户自动清除
        emptyContent(){
            this.$refs.addFormRef.resetFields();
        },
        //用户修改请求
        async selectUser (id) {
            const { data: res } = await this.$http.get('users/' + id)
            if (res.meta.status !== 200) {
                return this.$message.error('查询用户信息失败');
            }
            console.log(res);
            this.modifyForm = res.data;
            this.modifyUser = true;
        },
        // 用户修改并提交
        modifyUserInfo(){
            this.$refs.modifyUserRef.validate(async valid => {
                //判断状态
                if(!valid){
                    return this.$message.error("修改用户信息失败");
                }
                const { data: res } = await this.$http.put('users/'+this.modifyForm.id,{
                    name:this.modifyForm.username,
                    email: this.modifyForm.email,
                    mobile: this.modifyForm.mobile
                })
                //判断数据是否请求道
                if (res.meta.status !== 200) {
                    return this.$message.error('修改用户信息失败');
                }
                // 关闭对话框
                this.modifyUser = false;
                this.getUserList();
                this.$message.success('修改用户信息成功');
            })
        },
        //用户删除(根据id删除)
        removeUser(id) {
            this.$confirm("确定要删除该权限吗", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
            .then(async () => {
                const {data:res} = await this.$http.delete('users/' + id)
                if(res.meta.status != 200){
                    return this.$message.error('删除用户失败')
                }
                this.$message.success("删除成功!");
                this.getUserList();
            })
            .catch(() => {
                this.$message.info("已取消删除!");
            });     
        },
        // 分配角色弹出关闭清除
        outdistribution(){
            this.userInfo={};
            this.selectedRoleId='';
        },
        //分配用户请求
        async selectUserTow(userInfo){
            this.userInfo=userInfo
            const {data : res} = await this.$http.get("roles");
            if(res.meta.status != 200){
                return this.$message.error('查询角色信息失败')
            }     
            this.distributionUser=true;
            this.distributionForm=res.data
        },
        //分配用户校验
        async distributionUserInfo(){
            this.$refs.distributionUserRef.validate(async valid => {
            if(!valid){
                return this.$message.error('请选择需要分配的角色');
            }
            const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRoleId});

             // 判断数据是否请求到
            if (res.meta.status !== 200) {
                return this.$message.error('分配角色信息失败');
            }

            // 提示成功并关闭弹窗,刷新数据
            this.$message.success('修改角色信息成功');
            this.distributionUser = false;
            this.getUserList();
            });
        }
    }
}
</script>
<style lang="less">
</style>